var oList = document.getElementById('list'),
    oNext = document.getElementById('next'),
    oPrev = document.getElementById('prev'),
    oButtons = document.getElementById('buttons'),
    oContainer = document.getElementById('container'),
    oLi = oButtons.getElementsByTagName('li');
var timer = null,
    timer2 = null,
    flag = true;
    index = 0;
function moveImg(dis) {
    var time = 400;
    var eachTime = 20;
    var eachDis = dis/(time/eachTime);
    var newLeft = oList.offsetLeft + dis;
    flag = false;
    function eachMove() { 
        if(dis > 0 && oList.offsetLeft < newLeft || dis < 0 && oList.offsetLeft > newLeft) {
            oList.style.left = oList.offsetLeft + eachDis + 'px';
        }else {
            flag = true; 
            clearInterval(timer);
            oList.style.left = newLeft + 'px';

            if (newLeft == 0) {
                oList.style.left = -2600 + 'px';
            }
            if (newLeft == -3120) {
                oList.style.left = -520 + 'px';
            }
        }
        
    }
    timer = setInterval(eachMove, eachTime);
}
oNext.onclick = function () {
    if(!flag) return;
    moveImg(-520);
    if(index == 4) {
        index = 0;
    }else {
        index++;
    }
    activeDot();
}
oPrev.onclick = function () {
    if(!flag) return;
    moveImg(520);
    if(index == 0) {
        index = 4;
    }else {
        index--;
    }
    activeDot();
}
// 设置小圆点活跃状态
function activeDot() {
    for(var i = 0; i < oLi.length; i++) {
        if(oLi[i].className == 'active') {
            oLi[i].className = '';
            break;
        }
    }
    oLi[index].className = 'active';
}
// 给小圆点绑定点击事件
for(var i = 0 ;i<oLi.length;i++){
    oLi[i].value = i;
    (function(){
        oLi[i].onclick = function(){
            if(this.value == index) return;
            var offset = (this.value - index)* -520;
            moveImg(offset);
            index = this.value;
            activeDot();
        }
    })();
}
// 自动轮播
timer2 = setInterval(oNext.onclick, 2000);
oContainer.onmouseover = function(){
    clearInterval(timer2);
};
oContainer.onmouseout = function(){
    timer2 = setInterval(oNext.onclick, 2000);
};